const app = getApp()

Page({
  data: {
    messages: [],
    unreadCount: 0,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false
  },

  onLoad: function (options) {
    this.loadMessages()
    this.getUnreadCount()
  },

  onShow: function () {
    // 每次显示页面时刷新未读消息数量
    this.getUnreadCount()
  },

  onPullDownRefresh: function () {
    this.refreshMessages()
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载消息列表
  loadMessages: function () {
    if (this.data.loading) return

    this.setData({ loading: true })

    wx.request({
      url: app.globalData.baseUrl + '/getMessages',
      method: 'GET',
      data: {
        page: this.data.page,
        limit: this.data.limit
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code === 1) {
          const newMessages = res.data.data.list
          const hasMore = newMessages.length === this.data.limit
          
          this.setData({
            messages: this.data.page === 1 ? newMessages : [...this.data.messages, ...newMessages],
            hasMore: hasMore
          })
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载消息失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
        wx.stopPullDownRefresh()
      }
    })
  },

  // 刷新消息列表
  refreshMessages: function () {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadMessages()
  },

  // 加载更多
  loadMore: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadMessages()
    }
  },

  // 获取未读消息数量
  getUnreadCount: function () {
    wx.request({
      url: app.globalData.baseUrl + '/getUnreadMessageCount',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            unreadCount: res.data.data.count
          })
        }
      }
    })
  },

  // 标记所有消息为已读
  markAllRead: function () {
    wx.showModal({
      title: '确认操作',
      content: '确定要将所有消息标记为已读吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: app.globalData.baseUrl + '/markMessageRead',
            method: 'POST',
            data: {
              mark_all: 1
            },
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              if (res.data.code === 1) {
                wx.showToast({
                  title: '标记成功',
                  icon: 'success'
                })
                this.refreshMessages()
                this.getUnreadCount()
              } else {
                wx.showToast({
                  title: res.data.msg || '操作失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  // 删除所有已读消息
  deleteAllRead: function () {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除所有已读消息吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: app.globalData.baseUrl + '/deleteMessage',
            method: 'POST',
            data: {
              delete_all: 1
            },
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              if (res.data.code === 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.refreshMessages()
              } else {
                wx.showToast({
                  title: res.data.msg || '删除失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  // 点击消息
  onMessageTap: function (e) {
    const message = e.currentTarget.dataset.message
    
    // 如果消息未读，标记为已读
    if (!message.is_read) {
      this.markMessageRead(message.id)
    }

    // 根据消息类型跳转到相应页面
    if (message.type === 'allocation' && message.related_id) {
      // 跳转到任务详情页面
      wx.navigateTo({
        url: '/pages/tasks/tasks'
      })
    } else {
      // 显示消息详情
      wx.showModal({
        title: message.title,
        content: message.content,
        showCancel: false
      })
    }
  },

  // 标记单个消息为已读
  markMessageRead: function (messageId) {
    wx.request({
      url: app.globalData.baseUrl + '/markMessageRead',
      method: 'POST',
      data: {
        message_id: messageId
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code === 1) {
          // 更新本地消息状态
          const messages = this.data.messages.map(item => {
            if (item.id === messageId) {
              item.is_read = 1
              item.is_read_text = '已读'
            }
            return item
          })
          this.setData({ messages })
          this.getUnreadCount()
        }
      }
    })
  },

  // 删除单个消息
  deleteMessage: function (e) {
    const messageId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条消息吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: app.globalData.baseUrl + '/deleteMessage',
            method: 'POST',
            data: {
              message_id: messageId
            },
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              if (res.data.code === 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.refreshMessages()
              } else {
                wx.showToast({
                  title: res.data.msg || '删除失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  // 获取消息图标
  getMessageIcon: function (type) {
    const iconMap = {
      'allocation': '/images/message-allocation.png',
      'audit': '/images/message-audit.png',
      'system': '/images/message-system.png'
    }
    return iconMap[type] || '/images/message-default.png'
  }
})
